#include "bnb_controller.h"
extern "C" {
#include "lua.h"
#include "lauxlib.h"
#include "lualib.h"
}

void BNBController::
initialize () {
  /**
    * Initialize logger.
    */
  logger_init ("bnb.log", bnb_terminate);

  LOG ("Log system initialized, initializing BnB Controller.");

  /**
    * Initialize SDL.
    */
  initSDL();
  /**
    * Initialize Lua.
    */
  initLua();
  /**
    * Initialize video context.
    */
  vidContext = BNBVideoContext::getInstance();
  // TODO : resolution and default values should never be coded directly
  // but rather stored in a config file, loaded using a Lua interpreter.
  vidContext->initialize(1024, 768, false);

  LOG ("BnB Controller initialized successfully.");
}

void bnb_terminate (int exit_status) {
  BNBController::kill();

  if (exit_status == EXIT_SUCCESS) {
    cout << "BnB exited normally." << endl;
  }
  else {
    cerr << "BnB exited after a fatal error." << endl;
  }

  exit(exit_status);
}

void BNBController::
initSDL () {
  int status = SDL_Init (SDL_INIT_VIDEO|SDL_INIT_AUDIO|SDL_INIT_JOYSTICK);

  if (status != 0) {
    LOG_FATAL("Unable to initialize the SDL library (1.3).");
  }
  else {
    LOG("SDL 1.3 library initialized successfully.");
  }
}

void BNBController::
initLua () {
  luaState = luaL_newstate();
  luaL_openlibs(luaState);
  LOG("Lua initialized successfully.");
}

#ifdef TEST_BNB_CONTROLLER
int main (int argc, char** argv) {
  BNBController* BNBCtrl = BNBController::getInstance();
  BNBCtrl->initialize();
  SDL_Delay(3000);
  BNBCtrl->terminate();
  return EXIT_SUCCESS;
}
#endif

